#include "types.h"
#include "stat.h"
#include "user.h"
#include "fs.h"
#include "fcntl.h"
#include "boundedbuffer.h"
#define STACK_SIZE 512

struct BB* myBB;

void* producer()
{
  int i = 0;
  int* j = 0;
  for (i = 0;i<50;i++){
     j = malloc(sizeof(int));
     *j = i;
     semaphore_put(myBB,(void*)j);
     //printf(1, "producer %d put element %d in buffer\n", thread_getid(), *j);
  }
  thread_exit(0);
 return 0;
}

void* consumer()
{
  int i = 0;
  int* j = 0;
  for (i = 0;i<50;i++){
    // printf(1,"Before pop\n");
     j = (void*)semaphore_pop(myBB);
     //printf(1, "consumer %d poped element %d in buffer\n", thread_getid(), *j);
  }
  thread_exit(0);
 return 0;
}

void
threadTest(int num)
{
  int i = 0;
  void* threadStack;
  int threadsList[num];
  for (i = 0;i < num;i++)
  {
   threadStack = malloc(STACK_SIZE);
   if (i%2)
       threadsList[i] = thread_create(&consumer,threadStack,STACK_SIZE);
   else
       threadsList[i] = thread_create(&producer,threadStack,STACK_SIZE);
  }

  for(i = 0;i < num;i++)
  {
    thread_join(threadsList[i],0);
  }
}



int
main(int argc, char *argv[])
{
  
  if(argc < 2){
    printf(1,"Invalid argument");
    exit();
  }

  myBB = BB_create(10);
  threadTest(atoi(argv[1]));

  exit();
}  
